from rest_framework import serializers
from dvadmin.utils.json_response import DetailResponse
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.viewset import CustomModelViewSet
from ops.chatbot.models import ChatBot
from ops.chatbot.utils.base import check_sign, call_back
from ops.devops.utils.util_config import get_config


class ChatBotSerializer(CustomModelSerializer):
    """
    devops-序列化器
    """

    text = serializers.JSONField()

    class Meta:
        model = ChatBot
        fields = '__all__'
        read_only_fields = ["id"]
        # exclude = ('text', )


class ChatBotViewSet(CustomModelViewSet):
    """
    devops接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    # exclude_field = ['text']
    queryset = ChatBot.objects.all()
    serializer_class = ChatBotSerializer
    extra_filter_backends = []
    permission_classes = []
    search_fields = ["name"]

    def create(self, request, *args, **kwargs):
        # 获取配置
        conf = get_config('dd')
        # 获取post提交的body数据
        data = request.data

        # 校验签名，失败则直接return
        timestamp = request.META.get('HTTP_TIMESTAMP')
        sign = request.META.get('HTTP_SIGN')

        # 从data中获取数据
        tmp_webhook = data['sessionWebhook']
        sender_nick = data.get('senderNick', 'unknown')
        sender_id = data.get('senderId', 'unknown')

        # 校验签名
        sign_check = check_sign(app_secret=conf.get('app_secret'), timestamp=timestamp, sign=sign, tmp_webhook=tmp_webhook)

        if sign_check.get('code'):
            return DetailResponse(data=sign_check, msg="失败")

        # 分割数据，第一个字段做函数名，剩余字段做参数
        msg_list = data['text']['content'].split()

        # 调用call_back
        res = call_back(*msg_list, tmp_webhook=tmp_webhook, senderId=sender_id, senderNick=sender_nick)

        # 存数据库
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        # # 返回的结果为dict且状态码非零，则替换其中的content，否则删除content
        if isinstance(res, dict) and res.get('errCode'):
            data['text']['content'] = res.get('msg')
        else:
            del data['text']['content']

        return DetailResponse(data=data, msg="新增成功")
